package com.zzx.test.thread.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: NotifyTest
 * @Description: notify方法测试
 * @Author zhouzhixin
 * @Date 2021/11/2
 * @Version 1.0
 */
public class NotifyTest3 {

    public static void main(String[] args) {
        Test3 test = new Test3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                test.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                test.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                test.printC();
            }
        }, "C").start();
    }

}

class Test3 {

    private int num = 0;

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            while (num != 0) {
                condition1.await();
            }
            num = 1;
            System.out.println(Thread.currentThread().getName() + "->" + num);
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (num != 1) {
                condition2.await();
            }
            num = 2;
            System.out.println(Thread.currentThread().getName() + "->" + num);
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (num != 2) {
                condition3.await();
            }
            num = 0;
            System.out.println(Thread.currentThread().getName() + "->" + 3);
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
